package com.thoughtful.remoting.handler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.thoughtful.provider.ServiceProvider;
import com.thoughtful.provider.impl.ZkServiceProviderImpl;
import com.thoughtful.remoting.dto.RpcRequest;
import com.thougtful.factory.SingletonFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * @author yushun
 * @createTime 2022/10/18 - 15:51
 **/
@Slf4j
public class RpcRequestHandler {

    private final ServiceProvider serviceProvider;

    public RpcRequestHandler() {
        // 使用 Zookeeper 实现注册中心
        this.serviceProvider = SingletonFactory.getSingleton(ZkServiceProviderImpl.class);
    }

    /**
     * 处理 rpc 请求, 找到相应的方法, 调用并返回结果
     * @param rpcRequest    rpcRequest
     * @return              调用结果
     */
    public Object handler(RpcRequest rpcRequest) {
        Object providerService = serviceProvider.getService(rpcRequest.getRpcServiceName());
        return invokeTargetMethod(rpcRequest, providerService);
    }

    private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) {
        Object result = null;
        try {
            Method method = service.getClass().getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            result = method.invoke(service, rpcRequest.getParameters());
            log.info("Service: [{}] successful invoke method: [{}]", rpcRequest.getRpcServiceName(), rpcRequest.getMethodName());
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return result;
    }
}
